/* 
 * File:   main.cpp
 * Author: Vicky.H
 * Email:  eclipser@163.com
 */
#include "defer.h"
#include <iostream>


void sayHello(const char* name) {
    printf("hello %s\n", name);
}


void funTest() {
    printf("funTest 1\n");
    defer([]() {
        printf("defer c: %d\n", __LINE__); });
    defer([]() {
        printf("defer c: %d\n", __LINE__); });
    defer([]() {
        printf("defer c: %d\n", __LINE__); });
    printf("funTest 2\n");
}

#include <cstdarg>
void funTest2(const char* fmt, ...) {
    char buffer[1024] = {0};
    va_list argp;
    va_start(argp, fmt);
    vsprintf(buffer, fmt, argp);
    va_end(argp);
    std::cout << buffer << std::endl;
}

int max(int i, int j) {
    return i > j ? i : j;
}

/*
 * 
 */
int main(void) {
    defer([]() {
        printf("defer a: %d\n", __LINE__); });
    defer([]() {
        printf("defer a: %d\n", __LINE__); });
    defer([]() {
        printf("defer a: %d\n", __LINE__); });
    defer([](){
        sayHello("jack"); });

    {
        defer([](){ printf("defer b: %d\n", __LINE__); });
        defer([](){ printf("defer b: %d\n", __LINE__); });
        defer([](){ printf("defer b: %d\n", __LINE__); });
        std::cout << "in code scope" << std::endl;
    }
    
    std::cout << "\n---------------------------" << std::endl;
        
    std::cout << "Done 1" << std::endl;
    std::cout << "Done 2" << std::endl;
    std::cout << "Done 3" << std::endl;
    
    // throw "exception happen";
    
    std::cout << "\n---------------------------" << std::endl;
    
    funTest();
    
    std::cout << "\n---------------------------" << std::endl;
    
    defer([](){funTest2("%d %s %d %s", 1, " hello ", 2, " world ");});
    
    defer([](){
        printf("p1\n");
        printf("p2\n");
        printf("p3\n");});
        
    int result = 0;
    defer([](){
        int result = max(1,2);
        printf("2 result = %d\n", result);});
    printf("1 result = %d\n", result);

    std::cout << "Over!" << std::endl;
    
    return 0;
}
